package com.zzyl.nursing.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.BindingFamilyDto;
import com.zzyl.nursing.dto.QueryDeviceDataListDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyByPageVo;
import com.zzyl.nursing.vo.FamilyMemberVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.QueryDeviceDataListVo;
import com.zzyl.nursing.vo.health.HealthDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override

    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序端登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember, phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 保存或更新用户
     *
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone, 7, 11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);
    }

    @Autowired
    private ElderMapper elderMapper;

    /**
     * 新增(绑定家人)
     *
     * @param dto 绑定家人信息(小程序端传递的参数)
     * @return 绑定结果
     */
    @Override
    public void add(BindingFamilyDto dto) {
        Long familyId = UserThreadLocal.getUserId();
        if (familyId == null) {
            throw new BaseException("用户未登录");
        }
        String idCard = dto.getIdCard();
        String remark = dto.getRemark();
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCard));
        if (ObjectUtil.isEmpty(elder)) {
            throw new BaseException("该老人不存在");
        }
        Long elderId = elder.getId();
        LocalDateTime createTime = LocalDateTime.now();

        familyMemberMapper.batchInsert(elderId, familyId, remark, createTime);

    }

    /**
     * 查询家人列表
     *
     * @return 家人列表
     */
    @Override
    public List<FamilyMemberVo> my() {


        Long familyId = UserThreadLocal.getUserId();
        List<FamilyMemberVo> list = familyMemberMapper.selectFamilyMember(familyId);

        return list;
    }

    /**
     * 查看家人列表（分页查询)
     *
     * @return 家人列表
     */
    @Override
    public List<FamilyByPageVo> listByPage() {
        Long familyId = UserThreadLocal.getUserId();
        List<FamilyByPageVo> list = familyMemberMapper.listByPage(familyId);

        return list;
    }

    /**
     * 查询健康数据
     *
     * @param iotId 设备id(路径参数)
     * @return 健康数据
     */
    @Override
    public List<HealthDataVo> queryServiceProperties(String iotId) {
        String s = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        List<DeviceData> list = JSONUtil.toList(s, DeviceData.class);
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<HealthDataVo> healthDataVoList = new ArrayList<>();
        list.forEach(deviceData -> {
            HealthDataVo healthDataVo = new HealthDataVo();
            healthDataVo.setFunctionId(deviceData.getFunctionId());
            healthDataVo.setEventTime(deviceData.getAlarmTime());
            healthDataVo.setValue(deviceData.getDataValue());
            healthDataVoList.add(healthDataVo);
        });
        return healthDataVoList;
    }

    /**
     * 查询设备数据列表(按天)
     *
     * @param dto 查询参数
     * @return 设备数据列表
     */
    @Override
    public List<QueryDeviceDataListVo> queryDeviceDataListByDay(QueryDeviceDataListDto dto) {
        // 将查询开始和结束时间格式转换
        dto.setStartTimeDate(LocalDateTimeUtil.of(dto.getStartTime(), ZoneId.of("Asia/Shanghai")));
        dto.setEndTimeDate(LocalDateTimeUtil.of(dto.getEndTime(), ZoneId.of("Asia/Shanghai")));
        // 查询数据
        List<QueryDeviceDataListVo> vos = familyMemberMapper.queryDeviceDataListByDay(dto);
        // 非空判断
        if (CollUtil.isEmpty(vos)) {
            return Collections.emptyList();
        }
        List<QueryDeviceDataListVo> result = new ArrayList<>();
        // 遍历创建每小时的数据对象并跟查询到的数据做匹配,存入新集合
        for (int hour = 0; hour < 24; hour++) {
            QueryDeviceDataListVo dataVo = new QueryDeviceDataListVo();
            LocalTime time = LocalTime.of(hour, 0, 0); // 时、分、秒
            dataVo.setDateTime(time.toString());
            dataVo.setDataValue(0.0);
            vos.forEach(vo -> {
                if (time.equals(vo.getPeriod().toLocalTime())) {
                    dataVo.setDataValue(vo.getDataValue());
                    result.add(dataVo);
                    return;
                }
            });
            result.add(dataVo);
        }
        return result;
    }

    /**
     * 获取设备数据列表(按周)
     *
     * @param dto 查询参数
     * @return 设备数据列表
     */
    @Override
    public List<QueryDeviceDataListVo> queryDeviceDataListByWeek(QueryDeviceDataListDto dto) {
        // 将查询开始和结束时间格式转换
        dto.setStartTimeDate(LocalDateTimeUtil.of(dto.getStartTime(), ZoneId.of("Asia/Shanghai")));
        dto.setEndTimeDate(LocalDateTimeUtil.of(dto.getEndTime(), ZoneId.of("Asia/Shanghai")));

        // 查询数据
        List<QueryDeviceDataListVo> vos = familyMemberMapper.queryDeviceDataListByWeek(dto); // 按周查询的方法
        // 非空判断
        if (CollUtil.isEmpty(vos)) {
            return Collections.emptyList();
        }

        List<QueryDeviceDataListVo> result = new ArrayList<>();

        // 获取查询范围内的所有日期（从开始日期到结束日期）
        LocalDate startDate = dto.getStartTimeDate().toLocalDate();
        LocalDate endDate = dto.getEndTimeDate().toLocalDate();

        // 遍历每一天
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            QueryDeviceDataListVo dataVo = new QueryDeviceDataListVo();
            // 设置日期格式，例如 "2023-10-01"
            String time = currentDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
            dataVo.setDateTime(time);
            dataVo.setDataValue(0.0);

            // 查找匹配当前日期的数据
            vos.forEach(vo -> {
                LocalDate voDate = vo.getPeriod().toLocalDate();
                if (time.equals(voDate.toString())) {
                    dataVo.setDataValue(vo.getDataValue());
                    return;
                }
            });

            result.add(dataVo);
            // 移至下一天
            currentDate = currentDate.plusDays(1);
        }

        return result;
    }
}
